
package com.tocea.formation.rents;


import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.tocea.formation.books.BookImpl;
import com.tocea.formation.books.IBook;
import com.tocea.formation.library.NotEnoughtExemplaireException;
import com.tocea.formation.users.IUser;

public class RentManager implements IRentManager
{
        
    private final Set<IRent> rents;
    
    public RentManager() {
        super();
        rents = new HashSet<IRent>();
    }
    
    public void rentBook(IUser _user, IBook _book) throws NotEnoughtExemplaireException {
    	IRent rent = new Rent(_user, _book, ((Integer)this.rents.size()+1));
        rents.add(rent);
        _book.removeExemplaires();   
    }
    
    public void returnBook(IRent _rent) throws NotSuchRentException {
    
        if (rents.contains(_rent)) {
            throw new NotSuchRentException("this rent does not exist");
        }
        _rent.setreturnDate(new Date());
        BookImpl b = (BookImpl)_rent.getBook();
        b.addExemplaires();
    }
    
    public void returnBook(Integer _idRent) throws NotSuchRentException {
    
        boolean find = false;
        for (Iterator<IRent> iterator = rents.iterator(); !find && iterator.hasNext();) {
            IRent rent = iterator.next();
            if (rent.getId() == _idRent) {
                find = true;
                rent.setreturnDate(new Date());
                rent.getBook().addExemplaires();
            }           
        }
        if (!find) {
            throw new NotSuchRentException("this rent does not exist");
        }
        
    }
    
    public Set<IRent> getAllRents() {
        return rents;
    }

    
}
